﻿//#define debug

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.ServiceModel.Web;
using System.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Threading;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Management;
using System.Data.SQLite;
using System.IO;
using Utilities;

namespace WindowsService
{

    public partial class Service1 : ServiceBase
    {
        bool debug = false;

        public Service1()
        {
            InitializeComponent();
        }

        WebServiceHost host;

        protected override void OnStart(string[] args)
        {
            try
            {
                Thread Classesthread = new Thread(new ThreadStart(GetClassesThread));
                Thread EnpointThread = new Thread(new ThreadStart(CreateEndpointThread));

                Classesthread.Start();
                EnpointThread.Start();
                SQLite.InsertException("Servizio ed endpoint avviati correttamente");
            }
            catch (Exception ex)
            {
                SQLite.InsertException(ex.Message);
            }
           
        }

        protected override void OnStop()
        {

        }
        
        private void GetClassesThread()
        {
            WMI.Classes.LocalWMI.Tables.Clear();                                // Pulisco il DataSet per prevenire errori come "Tabella già esistente"
            WMI.Classes.GetClassesByScheduling();
            Utilities.SQLite.CreateTables(WMI.Classes.LocalWMI);
            Utilities.SQLite.InsertData(WMI.Classes.LocalWMI);
            GetDBXml();
        }

        private void CreateEndpointThread()
        {
            try
            {
                host = new WebServiceHost(typeof(WMIService.Service), new Uri(ConfigurationManager.AppSettings["endPoint"]));
                ServiceEndpoint sep = host.AddServiceEndpoint(typeof(WMIService.IService), new WebHttpBinding(), "");
                ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                sdb.IncludeExceptionDetailInFaults = true;
                sdb.HttpHelpPageEnabled = true;
                host.Open();
            }
            catch (Exception ex)
            {
                #if debug
		            System.IO.File.AppendAllText(Utilities.Utilities.GetInstallationFolder() + "Log.txt", "Endpoint! "+ex.Message + "\r\n");
	            #endif      
            }
        }

        private void CreateTable()
        {
            int table = 24;
            bool flag = true;
            while (flag)
            {
                if (WMI.Classes.LocalWMI.Tables.Count == table)
                {
                    flag = false;
                    Utilities.SQLite.CreateTables(WMI.Classes.LocalWMI);
                }
            }
 
        }

        private void GetDBXml()
        {

            string SQLitePath = Environment.ExpandEnvironmentVariables("%ProgramFiles%") + "\\sqlite.exe";
            Environment.SetEnvironmentVariable("PATH", Environment.ExpandEnvironmentVariables("PATH") + Environment.ExpandEnvironmentVariables("%ProgramFiles%"));
            
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.LoadUserProfile = true;
            psi.FileName = "cmd.exe";
            psi.Arguments = String.Format("/c  sqlite \"{0}Mynte.db\" .dump > \"{0}Mynte.dump\"", Utilities.Utilities.GetInstallationFolder());
            psi.WorkingDirectory = Environment.ExpandEnvironmentVariables("%ProgramFiles%");

            using (Process SQLite = Process.Start(psi))
            {
                SQLite.WaitForExit();
            }

            string cmdText = string.Empty;
            try
            {
                cmdText = System.IO.File.ReadAllText(Utilities.Utilities.GetInstallationFolder() + "Mynte.dump");
            }
            catch (Exception ex)
            {
                Utilities.SQLite.InsertException(ex.Message);
            }

            cmdText = cmdText.Replace("PRAGMA foreign_keys=OFF;", "");
            cmdText = cmdText.Replace("ON CONFLICT REPLACE", "");
            cmdText = cmdText.Replace(@"""", "");
            cmdText = cmdText.Replace("VARCHAR", "VARCHAR(255)");
            string[] d = cmdText.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            var sd = d.Where(a => a.Contains("CREATE TABLE"));
            List<string> asd = (from item in sd select item.Substring(13, item.IndexOf("(") - 13)).ToList();

            foreach (string item in asd)
            {
                cmdText = cmdText.Replace("CREATE TABLE " + item, string.Format("IF OBJECT_ID('{0}', 'U') IS  NULL CREATE TABLE {0}", item.Trim()));
            }



            try
            {
                using (SqlConnection conn = new SqlConnection(Environment.ExpandEnvironmentVariables(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString)))
                {
                    conn.Open();
                    using (SqlCommand comm = new SqlCommand(cmdText, conn))
                    {
                        comm.ExecuteNonQuery();
                    }
                }
            }

            catch (Exception ex)
            {
                #if debug
                    System.IO.File.AppendAllText(Utilities.Utilities.GetInstallationFolder() + "Log.txt", "113 " + ex.Message + cmdText + "\r\n"); 
                #endif
            }
        }


    }
}